<template>
  <div class="user-list">
    <UserAdd ref="useradd"></UserAdd>
    <el-button type="primary" icon="el-icon-plus" @click="handleAddClick">添加</el-button>
    <el-table
      :data="newTableData.filter(data => !search || data.username.toLowerCase().includes(search.toLowerCase()))"
      style="width: 100%;"
    >
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column
        align="right">
        <template slot="header" slot-scope="scope">
          <el-input
            v-model="search"
            size="mini"
            placeholder="输入关键字搜索"/>
        </template>
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="tableData.length"
        :page-size="pageSize"
        @current-change="handleChange"
        :hide-on-single-page="true"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getList, remove } from '@/api/user'
import UserAdd from './UserAdd'
export default {
  components: {
    UserAdd,
  },

  data() {
    return {
      tableData: [],
      search: '',
      currentPage: 1
    }
  },

  computed: {
    newTableData() {
      const start = (this.currentPage - 1) * this.pageSize
      return this.tableData.slice(start, start + this.pageSize)
    }
  },

  methods: {
    handleDelete(index, row) {
      
      this.$confirm('确认删除？')
        .then(async (_) => {
          const result = await remove({
            _id: row._id
          })

          // 重新拉取数据，刷新页面
          await this._loadData()

          let totalPage = Math.ceil(this.tableData.length / this.pageSize)

          // 只有在最后一页，最后一条被删除，才做this.currentPage--
          if (totalPage === this.currentPage - 1) {
            this.currentPage--
          }

          done();
        })
        .catch(_ => {});
    },

    handleAddClick() {
      this.$refs['useradd'].dialogVisible = true
    },

    handleChange(currentPage) {
      this.currentPage = currentPage
    },

    async _loadData() {
      let result = await getList()
      let data = result.data.data.map((value) => ({
        username: value.username,
        _id: value._id
      }))
      this.tableData = data
    }
  },

  created() {
    this.pageSize = 10
  },

  async mounted() {
    this._loadData()
  },
}
</script>

<style lang='scss' scoped>
.user-list {
  padding: 20px;
}
.pagination {
  padding: 10px;
  text-align: right;
}
</style>